package com.hx.tiffshare.service.impl;

import com.hx.tiffshare.mapper.TiffSegMapper;
import com.hx.tiffshare.service.ITiffSegService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.hx.tiffshare.entity.TiffSeg;
import com.hx.tiffshare.entity.AjaxResult;

@Service
public class TiffSegService implements ITiffSegService {

    private static Logger logger = LoggerFactory.getLogger(TiffSegService.class);

    @Autowired
    private TiffSegMapper tiffSegMapper;

    @Value("${oss.defaultRegion}")
    private String defaultRegion;

    @Override
    public AjaxResult validPassword(String password) {
        AjaxResult ajax = AjaxResult.success();
        try {
            String[] arr = password.split("_");
            long id = Long.parseLong(arr[1]);

            // 以"a1d3m4i5n6"结尾的密码，不需要考虑状态是否可用
            int admin = 0;
            if (password.startsWith("A1d3M4i5N6")) {
                admin = 1;
            }
            TiffSeg tiffSeg = tiffSegMapper.selectTiffByIdWithStatus(id, admin);
            if (tiffSeg == null) {
                return AjaxResult.error("数据已消失，请刷新页面重新操作！");
            }
            String sharePassword = tiffSeg.getSharePassword();
            String dziObjectName = tiffSeg.getDziObjectName();
            String previewUrl = defaultRegion + dziObjectName;
            // 以"a1d3m4i5n6"结尾的密码，直接返回预览url
            if (password.startsWith("A1d3M4i5N6")) {
                ajax.put("previewUrl", previewUrl);
                return ajax;
            }

            if (!password.equals(sharePassword)) {
                return AjaxResult.error("密码错误，请重新输入！");
            }
            ajax.put("previewUrl", previewUrl);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return ajax;
    }
}
